﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Oliving.Edge.VModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Oliving.Edge.Filter
{


    public class WebExceptionFilter : IExceptionFilter, IOrderedFilter
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<GlobalExceptionsFilter> _loggerHelper;
        public int Order { get; set; } = int.MaxValue - 10;



        public WebExceptionFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> loggerHelper)
        {
            _env = env;
            _loggerHelper = loggerHelper;
        }



        public void OnException(ExceptionContext context)
        {
            var _Exception = context.Exception;
            if (_Exception is MessageBox error)
            {
                context.ExceptionHandled = true;
                context.HttpContext.Response.StatusCode = 200;
                context.Result = new JsonResult(error.apiResult);
            }
            else
            {
                if (context.HttpContext.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    context.ExceptionHandled = true;
                    context.HttpContext.Response.StatusCode = 200;
                    context.Result = new JsonResult(new ApiResult((int)StatusCodeEnum.未授权, $"{StatusCodeEnum.未授权.ToString()}"));
                }
                else
                {

                    //Tools.Log.Write(_Exception, context.HttpContext.Connection.RemoteIpAddress.ToString());//nlog 写入日志到 txt

                    _loggerHelper.LogInformation(context.HttpContext.Connection.RemoteIpAddress.ToString());


                    context.Result = new JsonResult(new ApiResult((int)StatusCodeEnum.程序异常, $"服务端出现异常![异常消息：{_Exception.Message}]"));
                }

            }
        }

        /// <summary>
        /// 自定义返回格式
        /// </summary>
        /// <param name="throwMsg"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("\r\n【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}", new object[] { throwMsg,
                ex.GetType().Name, ex.Message, ex.StackTrace });
        }



    }


}
